package ele_handler

import (
	"encoding/json"
	"go-yuque/logger"
	"golang.org/x/net/html"
	"net/url"
	"strings"
)

type cardJsonI interface {
	codeBlockHandlerStruct |
	bookMarkLinkStruct |
	cardImageStruct |
	cardMathHandlerStruct |
	cardBoardHandlerStruct |
	cardLocaldocStruct |
	cardYuqueStruct
}

// 处理 card 元素中的 json 文本
func parseCardJson[T cardJsonI](node *html.Node, c *T) (rErr error) {
	rErr = nil
	if node != nil {
		codeBlockVal := findAttribute(node, "value")
		if len(codeBlockVal) > 0 {
			codeBlockVal = strings.Replace(codeBlockVal, "data:", "", 1)
			unescape, err := url.QueryUnescape(codeBlockVal)
			if err != nil {
				logger.Errorf("card urlDecode 解析异常:%v", err)
				return
			}
			err = json.Unmarshal([]byte(unescape), c)
			if err != nil {
				logger.Errorf("card json 解析异常:%v", err)
				return
			}
		}

		return
	}
	return
}
